from rest_framework import serializers
from django_redis import get_redis_connection


class RegisterSmscodeSerializers(serializers.Serializer):
    text = serializers.CharField(label="图片验证码", min_length=4, max_length=4, required=True)
    image_code_id = serializers.UUIDField(label="uuid", required=True)

    def validate(self, attrs):
        # 获取用户提交的图片验证码
        text = attrs.get("text")
        image_code_id = attrs.get("image_code_id")
        # 连接redis
        redis_conn = get_redis_connection("code")
        # 获取redis_text
        redis_text = redis_conn.get("img_%s" % image_code_id)
        # 判断是否过期
        if redis_text is None:
            raise serializers.ValidationError("验证码已过期")
        # 对比
        if redis_text.decode().lower() != text.lower():
            raise serializers.ValidationError("验证码不一致")

        return attrs
